package com.bb.blog.code.mybatis.mapper;

import com.alibaba.fastjson.JSONObject;
import org.apache.tomcat.util.http.fileupload.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.Resource;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Stream;

public class MapperXRegistry {
    private static Logger logger = LoggerFactory.getLogger(MapperXRegistry.class);
    private static Resource[] mapperLocation;


    private static Map<Class<?>, Object> knowMapper = new HashMap<>();
    private static Map<String, Map<String, String>> mapperXContent=new HashMap<>();

    public static void setMapperXLocation(Resource[] resources) {
        mapperLocation = resources;
    }

    public static void parseMapperx() {
        Stream.of(mapperLocation).forEach(resource -> {
            try {
                String fileName = resource.getFilename();
                Integer lastPoint = fileName.lastIndexOf(".");
                final String mapperXName = fileName.substring(0, lastPoint);

                JSONObject jsonObject = JSONObject.parseObject(resource.getInputStream(), JSONObject.class);
                Map<String, String> stringMap = new HashMap<>();
                jsonObject.keySet().forEach(k -> {
                    String content = jsonObject.getString(k);
                    stringMap.put(k, content);
                    mapperXContent.put(mapperXName, stringMap);
                });

            } catch (IOException e) {
                e.printStackTrace();
            }

        });
    }

    public static String resolveMapperContent(Class<?> mapperInterface, String methodName) {
        String content;
        Map<String, String> mapperContentMap;
        String clazzName = mapperInterface.getSimpleName();
        if ((mapperContentMap = mapperXContent.get(clazzName)) == null) {
            RuntimeException runtimeException = new RuntimeException("error!");
            logger.info("can find mapperX   " + clazzName + "'s content", runtimeException);
            throw runtimeException;
        }
        content = mapperContentMap.get(methodName);
        if (content == null) {
            RuntimeException runtimeException = new RuntimeException("error!");
            logger.info("can find mapperX   " + clazzName + "." + methodName + "'s content", runtimeException);
            throw runtimeException;
        }
        return content;


    }

    public static <T> void addMapper(Class<T> type, T o) {
        knowMapper.putIfAbsent(type, o);

    }

    public static <T> boolean hasMapper(Class<T> type) {
        boolean b = knowMapper.containsKey(type);
        return b;
    }

    public static <T> T getMapper(Class<T> type) {
        return (T) knowMapper.get(type);
    }

}

